<!DOCTYPE html>
<html>
<head>

    <title>noVNC</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

    <style type="text/css">

        body {
            margin: 0;
            background-color: dimgrey;
            height: 100%;
            display: flex;
            flex-direction: column;
        }

        html {
            height: 100%;
        }

        #top_bar {
            background-color: #6e84a3;
            color: white;
            font: bold 12px Helvetica;
            padding: 6px 5px 4px 5px;
            border-bottom: 1px outset;
            position: relative;
        }

        #status {
            text-align: center;
        }

        .btnList{
            position: absolute;
            top: 0;
            right: 0;
        }

        .sendButton {
            top: 0px;
            right: 0px;
            border: 1px outset;
            padding: 5px 5px 4px 5px;
            cursor: pointer;
            display: inline-block;
        }

        #screen {
            flex: 1; /* fill remaining space */
            overflow: hidden;
        }

    </style>

    <!-- Promise polyfill for IE11 -->
    <script src="vendor/promise.js"></script>

    <!-- ES2015/ES6 modules polyfill -->
    <script type="module">
        window._noVNC_has_module_support = true;
    </script>
    <script>
        window.addEventListener("load", function () {
            if (window._noVNC_has_module_support) return;
            const loader = document.createElement("script");
            loader.src = "vendor/browser-es-module-loader/dist/" +
                "browser-es-module-loader.js";
            document.head.appendChild(loader);
        });
    </script>

    <!--Jquery -->
    <script src="plugin/jquery/jquery-2.1.4.js"></script>

    <!-- layer -->
    <script src="plugin/layer/layer.js"></script>

    <!-- actual script modules -->
    <script type="module" crossorigin="anonymous">
        // RFB holds the API to connect and communicate with a VNC server
        import RFB from './core/rfb.js';

        let vncServer = "192.168.1.144:6080";
        let rfb;
        let desktopName;

        function connectedToServer(e) {
            status("Connected to " + desktopName);
        }

        function disconnectedFromServer(e) {
            if (e.detail.clean) {
                status("Disconnected");
            } else {
                status("Something went wrong, connection is closed");
            }
        }

        function credentialsAreRequired(e) {
            const password = prompt("Password Required:");
            rfb.sendCredentials({password: password});
        }

        function updateDesktopName(e) {
            desktopName = "";
            for(let i=0;i<e.detail.name.length;i++){
                if(e.detail.name.charCodeAt(i)!==0){
                    desktopName += e.detail.name.charAt(i);
                }
            }
        }

        function sendCtrlAltDel() {
            rfb.sendCtrlAltDel();
            return false;
        }

        function updateFullscreenButton() {
            if($("#sendFullScreenButton").text()==="fullScreen"){

                $("#top_bar").hide();
                $("#sendFullScreenButton").text("exitFullScreen");
            }else{
                $("#top_bar").show();
                $("#sendFullScreenButton").text("fullScreen");
            }
        }

        $("#sendFullScreenButton").click(function() {
            if (document.fullscreenElement || // alternative standard method
                document.mozFullScreenElement || // currently working methods
                document.webkitFullscreenElement ||
                document.msFullscreenElement) {
                if (document.exitFullscreen) {
                    document.exitFullscreen();
                } else if (document.mozCancelFullScreen) {
                    document.mozCancelFullScreen();
                } else if (document.webkitExitFullscreen) {
                    document.webkitExitFullscreen();
                } else if (document.msExitFullscreen) {
                    document.msExitFullscreen();
                }
            } else {
                if (document.documentElement.requestFullscreen) {
                    document.documentElement.requestFullscreen();
                } else if (document.documentElement.mozRequestFullScreen) {
                    document.documentElement.mozRequestFullScreen();
                } else if (document.documentElement.webkitRequestFullscreen) {
                    document.documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
                } else if (document.body.msRequestFullscreen) {
                    document.body.msRequestFullscreen();
                }

            }
            updateFullscreenButton();
        });

        // 用于全屏时ESC退出
        function checkFull(){
            let isFull =  document.fullscreenEnabled || window.fullScreen || document.webkitIsFullScreen || document.msFullscreenEnabled;

            if(isFull === undefined) isFull = false;
            return isFull;
        }

        window.onresize = function(){
            if(!checkFull()){
                $("#top_bar").show();
                $("#sendFullScreenButton").text("fullScreen");
            }
        };

        // Show a status text in the top bar
        function status(text) {
            document.getElementById('status').textContent = text;
        }

        function readQueryVariable(name, defaultValue) {
            const re = new RegExp('.*[?&]' + name + '=([^&#]*)'),
                match = document.location.href.match(re);
            if (typeof defaultValue === 'undefined') {
                defaultValue = null;
            }

            if (match) {
                return decodeURIComponent(match[1]);
            }

            return defaultValue;
        }


        let connect = function (password) {
            document.getElementById('sendCtrlAltDelButton')
                .onclick = sendCtrlAltDel;

            const host = readQueryVariable('host', window.location.hostname);
            let port = readQueryVariable('port', window.location.port);

            // | | |         | | |
            // | | | Connect | | |
            // v v v         v v v

            status("Connecting");

            // Build the websocket URL used to connect
            let url;
            if (window.location.protocol === "https:") {
                url = 'wss';
            } else {
                url = 'ws';
            }
            url += '://'+vncServer;
            if (host && port) {
                url += '?host=' + host + '&port=' + port;
            }
            console.log(url);
            // Creating a new RFB object will start a new connection
            rfb = new RFB(document.getElementById('screen'), url,
                {credentials: {password: password}});

            // Add listeners to important events from the RFB module
            rfb.addEventListener("connect", connectedToServer);
            rfb.addEventListener("disconnect", disconnectedFromServer);
            //rfb.addEventListener("credentialsrequired", credentialsAreRequired);
            rfb.addEventListener("desktopname", updateDesktopName);

            // Set parameters that can be changed on an active connection
            rfb.viewOnly = readQueryVariable('view_only', false);
            rfb.scaleViewport = readQueryVariable('scale', false);
        };
        layer.prompt({
            formType: 1,
            title: '请输入连接密码',
            offset: '100px',
            move:false,
            success:function(layero,index){
                let pwdDom = $(layero).children('.layui-layer-content').children('.layui-layer-input');
                pwdDom.on('keydown',function(e){
                    if(e.keyCode===13){
                        connect($(pwdDom).val());
                        layer.close(index);
                    }
                });

            }
        },function(value, index, elem){
            connect(value);
            layer.close(index);
        });

    </script>
</head>

<body>
<div id="top_bar">
    <div id="status">Loading</div>
    <div class="btnList">
        <div id="sendFullScreenButton" class="sendButton">fullScreen</div>
        <div id="sendCtrlAltDelButton" class="sendButton">Ctrl+Alt+Del</div>
    </div>
</div>
<div id="screen">
    <!-- This is where the remote screen will appear -->
</div>
</body>
</html>
